package com.example.classload;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.ProtectionDomain;

public class MyClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String fileName = name + ".class";

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i;
        byte[] b = new byte[1024];
        while(true) {
            try {
                if (!((i = fileInputStream.read()) != -1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            byteArrayOutputStream.write(b, 0, i);
        }

        byte[] byteArray = byteArrayOutputStream.toByteArray();

        return defineClass(name, byteArray, 0, byteArray.length);
    }
}
